<?php

namespace app\api\controller;

use app\api\model\DataUser;
use app\api\model\DataDistributionQueue;
use think\admin\Controller;
use app\data\model\ShopOrder;

use think\Request;
/**
 * Class Distribution
 * @package app\api\controller
 */
class Distribution extends Controller
{

    private $default_type = 'json';
    protected $middleware = ['check'];
    protected $level = array(
        '一级佣金','二级佣金'
    );
    protected $audit_status = array(
        '审核中','待打款','已打款','驳回'
    );
    /**
     * GET
     * 分销规则
     * @return void
     */
    public function center(){
         if($this->request->debug != 1){
            $detail = sysconf('distribution_agreement');
            if(empty($detail)) $detail = '测试  数据为空富文本';
            //判断状态
            $tokeninfo = $this->request->tokeninfo;
            $audit_remark = '';
            if(empty($tokeninfo) === FALSE){
                $is_distribution = 0;
                $distributionModel = new \app\api\model\DataUserDistribution();
                $DataUserModel = new \app\api\model\DataUser();
                $userinfo = $DataUserModel->getOne(array(
                        'id'  => $tokeninfo['id']
                    ),'is_distribution');
                if(empty($userinfo)){
                    $is_distribution = 0;
                }else{
                     if($userinfo['is_distribution'] == 0){//非分销员
                        //检测是否提交了申请
                        $applyinfo = $distributionModel->getOne(array(
                            'uuid'  => $tokeninfo['id'],
                            'status'=> 1
                        ));
                        if(empty($applyinfo) === FALSE){
                            $is_distribution = 1;//已审核成功
                        }else{
                            $applyinfo = $distributionModel->getOne(array(
                                'uuid'  => $tokeninfo['id'],
                                'status'=> 0
                            ),'id,audit_remark','',array(
                                'audit_time'    => 'desc'
                            ));
                            if(empty($applyinfo) === FALSE){
                                $is_distribution = 2;//审核中
                            }else{
                                $applyinfo = $distributionModel->getOne(array(
                                    'uuid'  => $tokeninfo['id'],
                                    'status'=> 2
                                ),'id,audit_remark','',array(
                                    'audit_time'    => 'desc'
                                ));
                                if(empty($applyinfo) === FALSE){
                                    $is_distribution = 3;//已驳回
                                    $audit_remark = $applyinfo['audit_remark'];
                                }
                            }
                        }
                    }else{
                         $is_distribution = 1;
                     }
                }
            }else{
                $is_distribution = 0;
            }
            return \Tools::returnMsg(true,array(
                'content'           => $detail,
                'is_distribution'   => $is_distribution,  //0 未申请  1已申请  2  申请中  3  已驳回
                'audit_remark'      => $audit_remark
            ),$this->default_type);
         }else{
            return \Tools::returnMsg(true,array(
                'content'           => '富文本内容',
                'is_distribution'   => 0,  //0 未申请  1已申请  2  申请中  3  已驳回
                'audit_remark'      => ''
            ),$this->default_type);
         }
    }

    /**
     * POST
     * 申请分销
     * @return void
     */
    public function apply(){
        if($this->request->debug != 1){
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false, array(
                        'code' => '100001',
                        'message' => '未登录'
                    ), $this->default_type);
            }
            $is_distribution = 0;
            if(isset($tokeninfo['is_distribution'])) {
                $is_distribution = $tokeninfo['is_distribution'];
            }
            if($is_distribution == 1){
                return \Tools::returnMsg(false, array(
                        'code' => '100011',
                        'message' => '已是分销员，无需重复申请'
                    ), $this->default_type);
            }
            $distributionModel = new \app\api\model\DataUserDistribution();
            $applyinfo = $distributionModel->getOne(array(
                'uuid'  => $tokeninfo['id'],
                'status'=> 0
            ));
            if(empty($applyinfo) === FALSE){
                return \Tools::returnMsg(false, array(
                        'code' => '100012',
                        'message' => '已提交申请，请耐心等待'
                    ), $this->default_type);
            }
            $res = $distributionModel->addData(array(
                'uuid'  => $tokeninfo['id'],
                'apply_time'=>\Tools::getDateTimeByTime()
            ));
            if($res){
                return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                return \Tools::returnMsg(false, array(
                    'code' => '100013',
                    'message' => '申请失败，请稍后重试'
                ), $this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,2,$this->default_type);
        }
    }

    /**
     * 分销记录
     * @return array|string
     */
    public function note(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $page = input('page',1,'trim,intval');
            $size = input('size',10,'trim,intval');
            $type = input('type', 0,'trim,intval');// 0  一级分销  1  二级分销
            $userModel = new \app\api\model\DataUser();
            $where['status'] = 1;
            if($type == 0){
                $where['pre_dis_id'] = $tokeninfo['id'];
            }else{
                $where['pre_pre_dis_id'] = $tokeninfo['id'];
            }
            $total = $userModel->checkNum($where);
            $lists = $userModel->getAllData($where,'username,headimg,id,create_at','',array(
                'create_at' => 'desc'
            ),array(($page-1)*$size,$size));
            if(empty($lists) === FALSE){
                $orderModel = new \app\api\model\ShopOrder();
                foreach($lists as &$lv){
                    $commissionInfo = $orderModel->getSum(array(
                        ['uuid','=', $lv['id']],
                        ['status','in','4,5,6']
                    ),'payment_amount');
                    $lv['commission_amount'] = sprintf("%.2f",$commissionInfo/100);
                }
            }
            return \Tools::returnMsg(true,array(
                'total'     => $total,
                'lists'     => $lists
            ),$this->default_type);
        }else{
            return \Tools::returnMsg(true,array(
                'total'     => 2,
                'lists'     => array(
                    array(
                        'username'  => '李思',
                        'headimg'   => '',
                        'create_at' => '2022-05-15 15:12:00',
                        'commission_amount'=>'50.00'
                    ),
                    array(
                        'username'  => '王五',
                        'headimg'   => '',
                        'create_at' => '2022-05-15 15:12:00',
                        'commission_amount'=>'50.00'
                    )
                )
            ),$this->default_type);
        }
    }
    /**
     * GET
     * 我的佣金
     * @return void
     */
    public function commission(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $userAccountModel = new \app\api\model\DataUserAccount();
            $accountInfo = $userAccountModel->getOne(array(
                'uuid'  => $tokeninfo['id']
            ),'avail_amount,all_amount,wait_amount,used_amount,freeze_amount,withdraw_amount');
            if(empty($accountInfo) === FALSE){
                $accountInfo['avail_amount'] = sprintf("%.2f",$accountInfo['avail_amount']/100);//可用
                $accountInfo['all_amount'] = sprintf("%.2f",$accountInfo['all_amount']/100);//总佣金
                $accountInfo['wait_amount'] = sprintf("%.2f",$accountInfo['wait_amount']/100);//待结算
                $accountInfo['used_amount'] = sprintf("%.2f",$accountInfo['used_amount']/100);//已使用
                $accountInfo['freeze_amount'] = sprintf("%.2f",$accountInfo['freeze_amount']/100);//冻结中
                $accountInfo['withdraw_amount'] = sprintf("%.2f",$accountInfo['withdraw_amount']/100);//已提现
                $accountInfo['avail_amount'] = $accountInfo['avail_amount'] - $accountInfo['freeze_amount'];
                $accountInfo['remark'] = sysconf('withdraw_remark');
                $commission_status_remark = sysconf("commission_status_remark");
                $accountInfo['commission_status_remark'] = isset($commission_status_remark) ? $commission_status_remark : '';
                $rate = sysconf('withdraw_rate');
                $accountInfo['withdraw_rate'] = !isset($rate) ? 0.06 : $rate/100;
                //本月预估
                $data_amount = self::getPreAmount(array(
                    'user_id'    =>$tokeninfo['id']
                ));
                $accountInfo['pre_amount'] = sprintf("%.2f",$data_amount/100)??0;
                return \Tools::returnMsg(true,$accountInfo,$this->default_type);
            }else{
                return \Tools::returnMsg(true,[],$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,array(
                'avail_amount'  => '12.00',
                'all_amount'  => '12.00',
                'wait_amount'  => '12.00',
                'used_amount'  => '12.00',
                'freeze_amount'  => '12.00',
                'remark'  => '每月25号之后可提现，提现审核一般5个工作日完成',
            ),$this->default_type);
        }
    }

    /**
     * 本月预估收益
     * @param $data
     * @return void
     */
    private function getPreAmount($data){
        $date = \Tools::getDateTimeByTime('d',time());
//            if($date < '7'){
//                $start_time = \Tools::getDateTimeByTime(time(),'Y-m').'-01 00:00:01';
//            }else{
//                $start_time = \Tools::getDateTimeByTime(strtotime("-1 months"),'Y-m').'-01 00:00:01';
//            }
            $end_time = \Tools::getDateTimeByTime();
            $pre_child = \app\data\model\DataUser::mk()->where(['pre_dis_id'=>$data['user_id']])
                ->column('id');
            //获取分销员的间接分销员
            $pre_pre_child = \app\data\model\DataUser::mk()->where(['pre_pre_dis_id'=>$data['user_id']])
                ->column('id');
            $forderAmount = 0;
            if(empty($pre_child) === FALSE){
                //获取对应分销员订单
                $pre_child_arr = array_chunk($pre_child,50);
                foreach($pre_child_arr as &$pfv){
                    $forderAmount += ShopOrder::mk()->whereIn('uuid',implode(',',$pfv))
                        ->where(array('has_settle_account'=>0,'channel'=>0))
                        ->whereIn('payment_type','0,1')
                        ->whereIn('status', '4,5,6')
                        ->sum('payment_amount');
                }

            }
            $sorderAmount = 0;
            if(empty($pre_pre_child) === FALSE){
                $pre_pre_child_arr = array_chunk($pre_pre_child,50);

                foreach($pre_pre_child_arr as &$psv) {
                    //获取对应分销员订单
                    $sorderAmount += ShopOrder::mk()->whereIn('uuid', implode(',', $psv))
                        ->where(array('has_settle_account'=>0,'channel'=>0))
                        ->whereIn('payment_type', '0,1')
                        ->whereIn('status', '4,5,6')
                        ->sum('payment_amount');
                }
            }

            //计算佣金比例
        $res_amount = $res_sec_amount = 0;
        if($forderAmount > 0){
            $res_amount = \Common::getLevel(1,$forderAmount);
        }
        if($sorderAmount > 0){
            $res_sec_amount = \Common::getLevel(0,$sorderAmount);
        }
        return $res_sec_amount + $res_amount;
    }
    /**
     * GET
     * 我的佣金明细
     * @return void
     */
    public function commissionnote(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $type = input('type',0,'trim,intval');//0  全部  1  佣金入账  2  佣金抵扣
            $page = input('page',1,'trim,intval');//当前页
            $size = input('size',10,'trim,intval');//每页数量
            $comminssionModel = new \app\api\model\DataUserCommission();
            $searchWhere = array(
                'uuid'  => $tokeninfo['id']
            );
            $whereIn = [];
            if($type == 0){
                $whereIn = array(
                    'status'    => '0,1'
                );
            }elseif ($type == 1){//已结算
                $searchWhere['type'] = 0;
                $searchWhere['status'] = 1;
            }elseif ($type == 2){//抵扣
                $searchWhere['type'] = 1;
                $searchWhere['status'] = 0;
            }
            $total = $comminssionModel->getNum($searchWhere,$whereIn);
            $lists = $comminssionModel->getLists($searchWhere,$whereIn,
                'order_no,used_order_no,created_at,amount,commission_amount,status,product_uuid,product_level',
                '',array(
                    'created_at'    =>'desc'
                ),array(
                    ($page-1)*$size,$size
                )
            );
            if(empty($lists) === FALSE){
                foreach($lists as &$lv){
                    if($lv['type'] == 0){
                         $lv['amount']   = sprintf("%.2f",$lv['amount']/100);
                        $lv['commission_amount']   = sprintf("%.2f",$lv['commission_amount']/100);
                    }else{
                        $lv['amount']   = sprintf("%.2f",$lv['amount']/100);
                        $lv['commission_amount']   = -sprintf("%.2f",$lv['commission_amount']/100);
                    }
                    $lv['created_at'] = \Tools::getDateTimeByTime(strtotime($lv['created_at']),'Y-m-d');
                }
            }
            return \Tools::returnMsg(true,array(
                'total' => $total,
                'lists' => $lists
            ),$this->default_type);
        }else{
            return \Tools::returnMsg(true,array(
                'total' => 2,
                'lists' => array(
                    array(
                        'status_name'   => '已结算',
                        'created_at'    => '2022-05-12 12:10:00',
                        'username'      => '李思',
                        'level_name'    => '一级佣金',
                        'amount'        => '4500.00',
                        'commission_amount'=>'50.00',
                        'orderlists'    => array(
                            array(
                                'goods_abridgeimg'  => '/static/img/goods/p1.jpg',
                                'goods_cover'  => '/static/img/goods/p1.jpg',
                                'goods_name'        => '商品商品商品商品商品商品商品商品',
                                'goods_spec'        => '白色 15英寸',
                                'price_selling'     => '130.00',
                                'stock_sales'     => 2,
                            ),
                            array(
                                'goods_abridgeimg'  => '/static/img/goods/p2.jpg',
                                'goods_cover'  => '/static/img/goods/p1.jpg',
                                'goods_name'        => '商品商品商品商品商品商品商品商品',
                                'goods_spec'        => '黑色 15英寸',
                                'price_selling'     => '130.00',
                                'stock_sales'     => 1,
                            )
                        )
                    ),
                    array(
                        'status_name'   => '已结算',
                        'created_at'    => '2022-05-12 12:10:00',
                        'username'      => '李思',
                        'level_name'    => '一级佣金',
                        'amount'        => '4500.00',
                        'commission_amount'=>'50.00',
                        'orderlists'    => array(
                            array(
                                'goods_abridgeimg'  => '/static/img/goods/p1.jpg',
                                'goods_cover'  => '/static/img/goods/p1.jpg',
                                'goods_name'        => '商品商品商品商品商品商品商品商品',
                                'goods_spec'        => '白色 15英寸',
                                'price_selling'     => '130.00',
                                'stock_sales'     => 2,
                            ),
                            array(
                                'goods_abridgeimg'  => '/static/img/goods/p2.jpg',
                                'goods_cover'  => '/static/img/goods/p1.jpg',
                                'goods_name'        => '商品商品商品商品商品商品商品商品',
                                'goods_spec'        => '黑色 15英寸',
                                'price_selling'     => '130.00',
                                'stock_sales'     => 1,
                            )
                        )
                    ),
                )
            ),$this->default_type);
        }
    }
    /**
     * POST
     * 我的佣金提现
     * @return void
     */
    public function withdraw(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $amount = input('amount',0,'trim,intval');
            $remark = input('remark','','trim');//备注
            if($amount > 0){
                //判断当前用户账户状态
                $userModel = new \app\api\model\DataUser();
                $userinfo = $userModel->getOne([
                    'id'    => $tokeninfo['id']
                ],'status');//后台冻结账户不允许提现
                if($userinfo['status'] != 1){
                    return \Tools::returnMsg(false, array(
                        'code' => '100014',
                        'message' => '账户异常，请联系管理员'
                    ), $this->default_type);
                }
                $userAccountModel = new \app\api\model\DataUserAccount();
                $accountInfo = $userAccountModel->getOne(array(
                    'uuid'  => $tokeninfo['id']
                ),'bank_name,bank_child_name,bank_code,invoice_name,avail_amount,freeze_amount');
                $availAmount = $accountInfo['avail_amount'] - $accountInfo['freeze_amount'];
                if($availAmount < $amount * 100){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '可提现佣金不足'
                    ), $this->default_type);
                }
                //TODO 提现手续费费
                $withdraw_rate = sysconf('withdraw_rate');
                if(!isset($withdraw_rate) || !is_numeric($withdraw_rate)) $withdraw_rate = 6;//6%
                $withdraw_amount = $amount * $withdraw_rate;
                //冻结额度
                //添加记录
                $opera = [];
                $userAccountModel->startTrans();
                $opera[] = $userAccountModel->incNum(array(
                    'uuid'  => $tokeninfo['id']
                ),'freeze_amount',$amount*100);
                $transferModel = new \app\api\model\DataUserTransfer();
                $opera[] = $transferModel->addData(array(
                    'uuid'      => $tokeninfo['id'],
                    'date'      => \Tools::getDateTimeByTime(time(),'Y-m-d'),
                    'code'      => \Common::uniqidDate(16,'W'),
                    'charge_rate'=> $withdraw_rate,
                    'charge_amount'=> $withdraw_amount,
                    'amount'    => $amount*100,
                    'bank_name' => $accountInfo['bank_name'],
                    'bank_bran'=>$accountInfo['bank_child_name'],
                    'bank_user'=> $accountInfo['invoice_name'],
                    'bank_code' => $accountInfo['bank_code'],
                    'remark' => $remark,
                    'create_at' =>\Tools::getDateTimeByTime()
                ));
                if(\Tools::checkArrayResult($opera)){
                    $userAccountModel->commit();
                    //TODO 发短信
                    return \Tools::returnMsg(true,$opera,$this->default_type);
                }else{
                    $userAccountModel->rollBack();
                    return  \Tools::returnMsg(false,array(
                        'code'  => '90002',
                        'message'=> '提现失败，请重试'
                    ),$this->default_type);
                }
            }else{
                return \Tools::returnMsg(false, array(
                    'code' => '10004',
                    'message' => '参数有误'
                ), $this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,1,$this->default_type);
        }
    }

    /**
     * 提现记录
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function withdrawnote(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $page = input('page',1,'trim,intval');
            $size = input('size',1,'trim,intval');
            $transferModel = new \app\api\model\DataUserTransfer();
            $total = $transferModel->checkNum(array(
                'uuid'  => $tokeninfo['id']
            ));
            $lists = $transferModel->getAllData(array(
                'uuid'  => $tokeninfo['id']
            ),'date,id,amount,audit_status','',[],array(($page-1)*$size,$size));
            if(empty($lists) === FALSE){
                foreach($lists as &$lv){
                    $lv['audit_status_name'] = $this->audit_status[$lv['audit_status']];
                    $lv['amount'] = sprintf("%.2f",$lv['amount']/100);
                }
            }
            return \Tools::returnMsg(true,array(
                'total' => $total,
                'lists' => $lists
            ),$this->default_type);
        }else{
            return \Tools::returnMsg(true,array(
                'total' =>2,
                'lists' => array(
                    array(
                        'id'    => 1,
                        'date'  => '2022-09-12',
                        'amount'=> '150.00',
                        'audit_status_name' => '已打款'
                    ),
                    array(
                        'id'    => 2,
                        'date'  => '2022-08-12',
                        'amount'=> '150.00',
                        'audit_status_name' => '已打款'
                    )
                )
            ),$this->default_type);
        }
    }

    /**
     * 提现明细
     * @return array|string|void
     */
    public function withdrawinfo(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $id = input('id','','trim,intval');
            if(empty($id)){
                return \Tools::returnMsg(false, array(
                    'code' => '10004',
                    'message' => '参数有误'
                ), $this->default_type);
            }
            $transferModel = new \app\api\model\DataUserTransfer();
            $info = $transferModel->getOne(array(
                'uuid'  => $tokeninfo['id'],
                'id'    => $id
            ));
            if(empty($info)){
                return \Tools::returnMsg(false, array(
                    'code' => '10004',
                    'message' => '参数有误'
                ), $this->default_type);
            }
            $info['amount'] = sprintf("%.2f",$info['amount']/100);
            $info['charge_amount'] = sprintf("%.2f",$info['charge_amount']/100);
            $info['audit_status_name'] = $this->audit_status[$info['audit_status']];
            return \Tools::returnMsg(true,$info,$this->default_type);
        }else{
            return \Tools::returnMsg(true,array(
                'create_at' => '2022-05-19 12:15:00',
                'audit_datetime' => '2022-05-19 12:15:00',
                'trade_time' => '2022-05-19 12:15:00',
                'charge_amount' => '5.00',
                'amount'    => 500.00,
                'bank_name'=>'建设银行',
                'bank_bran'=>'大望路支行',
                'bank_user'=>'李思',
                'bank_code'=>'4545455****45445',
                'remark'=>'备注',
                'audit_status_name'=>'已打款',
                'audit_remark'=>'',
                'path'=>'/static/img/goods/p3.jpg'
            ),$this->default_type);
        }
    }
}
